//获取地址栏参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    // 解决获取中文乱码
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

/**
 * 判断值是否不为空
 * @param {Object} val
 */
function isNotNull(val) {
    if (val !== 'undefined' && val !== "" && val != null) {
        return true
    }
    return false
}

/**
 * 生成uuid
 */
function guid() {
    let uuid = ''
    for (let i = 0; i < 8; i++) {
        if (i == 0) {
            uuid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
        } else {
            uuid += (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
        }
    }
    return uuid
}

/**
 * 生成一个用不重复的ID(可指定位数和前缀)
 */
function getUuiD(length, preffix) {
    //timestamp为当前时间戳
    let timestamp = (new Date()).getTime()
    length = length - 13;
    let str = "";
    let str_arr = [
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    for (let i = 0; i < length; i++) {
        let r = parseInt(Math.random() * 9);//生成0-62之间的随机数
        str += str_arr[r];
    }
    let res_str = preffix + str + timestamp
    return res_str;
}

/**
 * 通用下载Excel
 * 后端直接返回文件流即可
 */
function downloadExcel(url, params, fileName, method) {
    let myMsg = layer.msg("正在下载...", {
        icon: 16,
        time: -1
    })
    // 默认是GET
    if (method !== 'GET' && method !== 'POST') {
        method = 'GET'
    }
    // 使用XMLHttpRequest 发送请求去下载
    var xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    if (method === 'GET') {
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    } else if (method === 'POST') {
        xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    } else {
        return;
    }
    xhr.responseType = 'blob';
    xhr.onload = function () {
        if (xhr.status === 200) {
            const blob = new Blob([xhr.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
            const elink = document.createElement('a')
            elink.download = fileName ?? '数据导出.xlsx'
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
        } else {
            console.error('Request failed.  Returned status of ' + xhr.status);
        }
        layer.msg("下载完成");
        layer.close(myMsg);//手动关闭
    };
    if (params) {
        // 组装参数
        if (method === 'GET') {
            var formData = Object.keys(params).map(function (key) {
                return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
            }).join('&');
            xhr.send(formData);
        } else if (method === 'POST') {
            xhr.send(JSON.stringify(params));
        }
    } else {
        xhr.send();
    }

}

/**
 * 处理数据下载到本地Excel中
 * @param headers 表头 map
 * @param data 数据 与表头对应
 * @param name 导入的文件名称
 */
function listTurnExcel(headers, data, name) {
    if (data.length === 0) {
        return;
    }

    // 将数据转换为工作表，并使用映射将键转换为相应的表头
    const sheetData = data.map(item => {
        const sheetItem = {};
        for (const key in headers) {
            sheetItem[headers[key]] = item[key];
        }
        return sheetItem;
    });
    // 将数据转换为工作表
    const sheet = XLSX.utils.json_to_sheet(sheetData, {
        header: Object.values(headers)
    });
    if (!isNotNull(name)) {
        name = '新建文件.xlsx';
    }
    // 创建工作簿并将工作表添加到其中
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, sheet);
    // 将工作簿写入二进制字符串并下载到本地计算机
    const workbookBinary = XLSX.write(workbook, {bookType: "xlsx", type: "binary"});
    const workbookArray = new Uint8Array(workbookBinary.length);
    for (let i = 0; i < workbookBinary.length; i++) {
        workbookArray[i] = workbookBinary.charCodeAt(i);
    }
    const blob = new Blob([workbookArray], {type: "application/octet-stream"});
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;

    link.download = name;
    link.click();
    URL.revokeObjectURL(url);
}

function hideStr(str, num) {
    if (isNotNull(str)) {
        return str.length > num ? str.slice(0, num) + '...' : str;
    } else {
        return '';
    }
}

/**
 * 格式化时间字符串
 *
 * `${year}年${month}月${day}日
 *
 */
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}/${month}/${day}`;
}

/**
 * 获取当前时间并格式化为yyyy-MM-dd HH:mm:ss函数
 * @return 得到类似 2021-06-23 12:07:33 的值
 */
function _getTimes() {
    const thisDay= new Date();
    const year = thisDay.getFullYear();       //年
    const month = thisDay.getMonth() + 1;     //月
    const day = thisDay.getDate();            //日
    const hh = thisDay.getHours();            //时
    const mm = thisDay.getMinutes();          //分
    const ss = thisDay.getSeconds();          //秒
    let timer = year + "-";
    if(month < 10)
        timer += "0";
    timer += month + "-";
    if(day < 10)
        timer += "0";
    timer += day + " ";
    if(hh < 10)
        timer += "0";
    timer += hh + ":";
    if (mm < 10)
        timer += '0';
    timer += mm + ":";
    if (ss < 10)
        timer += '0';
    timer += ss;
    return (timer);
}
